package com.example.testplatform.controller;

import com.example.testplatform.common.LogUtils;
import com.example.testplatform.common.Result;
import com.example.testplatform.entity.Role;
import com.example.testplatform.service.RoleService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 角色管理控制器
 * 处理角色的CRUD操作
 */
@RestController
@RequestMapping("/api/system/roles")
public class RoleManageController {
    
    private static final Logger logger = LogUtils.getLogger(RoleManageController.class);
    
    @Autowired
    private RoleService roleService;
    
    /**
     * 获取所有角色
     * @return 角色列表
     */
    @GetMapping
    public Result<List<Role>> getAllRoles() {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "ROLE_QUERY_ATTEMPT", "system", "尝试获取所有角色列表");
        LogUtils.logApiRequest(logger, "GET", "/api/system/roles", null);
        LogUtils.debug(logger, () -> "开始处理获取所有角色列表请求");
        
        try {
            LogUtils.info(logger, () -> "执行获取所有角色列表操作");
            List<Role> roles = roleService.getAllRoles();
            
            LogUtils.debug(logger, () -> "获取角色列表成功，共获取到" + (roles != null ? roles.size() : 0) + "个角色");
            LogUtils.logBusiness(logger, "ROLE_QUERY_SUCCESS", "system", "获取所有角色列表成功，数量=" + (roles != null ? roles.size() : 0));
            LogUtils.logPerformance(logger, "getAllRoles", startTime, System.currentTimeMillis());
            
            LogUtils.info(logger, () -> "获取所有角色列表请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
            return Result.success(roles);
        } catch (Exception e) {
            LogUtils.logApiError(logger, "GET", "/api/system/roles", e);
            LogUtils.error(logger, "获取角色列表过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "ROLE_QUERY_FAILED", "system", "获取角色列表失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "getAllRoles", startTime, System.currentTimeMillis());
            return Result.fail("获取角色列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 分页查询角色列表
     * @param page 页码
     * @param pageSize 每页数量
     * @param params 查询参数
     * @return 角色列表和总数
     */
    @GetMapping("/page")
    public Result<Map<String, Object>> getRoleList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Map<String, Object> params) {
        long startTime = System.currentTimeMillis();
        
        // 保存原始参数的final版本用于日志记录
        final Integer originalPage = page;
        final Integer originalPageSize = pageSize;
        
        LogUtils.logBusiness(logger, "ROLE_PAGE_QUERY_ATTEMPT", "system", "尝试分页查询角色列表");
        LogUtils.logApiRequest(logger, "GET", "/api/system/roles/page", "page=" + page + ", pageSize=" + pageSize + ", params=" + (params != null ? params.toString() : "空"));
        LogUtils.debug(logger, () -> "开始处理分页查询角色列表请求，页码=" + originalPage + ", 每页数量=" + originalPageSize);
        
        try {
            // 验证参数
            if (page == null || page <= 0) {
                LogUtils.warn(logger, "分页查询参数无效: 页码必须大于0，当前页码=" + page);
                LogUtils.logBusiness(logger, "ROLE_PAGE_QUERY_FAILED", "system", "分页查询参数无效: 页码必须大于0");
                page = 1;
                LogUtils.debug(logger, () -> "自动修正页码为默认值1");
            }
            
            if (pageSize == null || pageSize <= 0 || pageSize > 1000) {
                LogUtils.warn(logger, "分页查询参数无效: 每页数量必须在1-1000之间，当前值=" + pageSize);
                LogUtils.logBusiness(logger, "ROLE_PAGE_QUERY_FAILED", "system", "分页查询参数无效: 每页数量必须在1-1000之间");
                pageSize = 10;
                LogUtils.debug(logger, () -> "自动修正每页数量为默认值10");
            }
            
            // 创建处理后参数的final版本
            final Integer finalPage = page;
            final Integer finalPageSize = pageSize;
            
            LogUtils.info(logger, () -> "执行分页查询角色列表操作，页码=" + finalPage + ", 每页数量=" + finalPageSize);
            Map<String, Object> result = roleService.getRoleList(page, pageSize, params);
            
            LogUtils.debug(logger, () -> "分页查询角色列表成功，返回结果包含total和list字段");
            LogUtils.logBusiness(logger, "ROLE_PAGE_QUERY_SUCCESS", "system", "分页查询角色列表成功，页码=" + finalPage + ", 每页数量=" + finalPageSize);
            LogUtils.logPerformance(logger, "getRoleList", startTime, System.currentTimeMillis());
            
            LogUtils.info(logger, () -> "分页查询角色列表请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
            return Result.success(result);
        } catch (Exception e) {
            LogUtils.logApiError(logger, "GET", "/api/system/roles/page", e);
            LogUtils.error(logger, "查询角色列表过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "ROLE_PAGE_QUERY_FAILED", "system", "查询角色列表失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "getRoleList", startTime, System.currentTimeMillis());
            return Result.fail("查询角色列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取角色
     * @param id 角色ID
     * @return 角色信息
     */
    @GetMapping("/{id}")
    public Result<Role> getRoleById(@PathVariable Long id) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "ROLE_DETAIL_QUERY_ATTEMPT", "system", "尝试根据ID获取角色详情");
        LogUtils.logApiRequest(logger, "GET", "/api/system/roles/" + id, null);
        LogUtils.debug(logger, () -> "开始处理根据ID获取角色详情请求，角色ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "根据ID获取角色详情参数无效: 角色ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "ROLE_DETAIL_QUERY_FAILED", "system", "根据ID获取角色详情参数无效: 角色ID必须大于0");
                return Result.fail("角色ID无效");
            }
            
            LogUtils.info(logger, () -> "执行根据ID获取角色详情操作，角色ID=" + id);
            Role role = roleService.getRoleById(id);
            
            if (role == null) {
                LogUtils.warn(logger, "根据ID获取角色详情失败: ID为" + id + "的角色不存在");
                LogUtils.logBusiness(logger, "ROLE_DETAIL_QUERY_FAILED", "system", "角色不存在，ID=" + id);
                return Result.fail("角色不存在");
            }
            
            LogUtils.debug(logger, () -> "获取角色详情成功，角色ID=" + id + ", 角色名称=" + role.getRoleName() + ", 角色代码=" + role.getRoleCode());
            LogUtils.logBusiness(logger, "ROLE_DETAIL_QUERY_SUCCESS", "system", "获取角色详情成功，角色ID=" + id + ", 角色名称=" + role.getRoleName());
            LogUtils.logPerformance(logger, "getRoleById", startTime, System.currentTimeMillis());
            
            LogUtils.info(logger, () -> "根据ID获取角色详情请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
            return Result.success(role);
        } catch (Exception e) {
            LogUtils.logApiError(logger, "GET", "/api/system/roles/" + id, e);
            LogUtils.error(logger, "获取角色信息过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "ROLE_DETAIL_QUERY_FAILED", "system", "获取角色信息失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "getRoleById", startTime, System.currentTimeMillis());
            return Result.fail("获取角色信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建角色
     * @param role 角色信息
     * @return 创建结果
     */
    @PostMapping
    public Result<String> createRole(@RequestBody Role role) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "ROLE_CREATE_ATTEMPT", "system", "尝试创建新角色");
        LogUtils.logApiRequest(logger, "POST", "/api/system/roles", role != null ? role.toString() : "空请求");
        LogUtils.debug(logger, () -> "开始处理创建角色请求");
        
        try {
            // 验证请求对象
            if (role == null) {
                LogUtils.warn(logger, "创建角色失败: 角色信息对象为空");
                LogUtils.logBusiness(logger, "ROLE_CREATE_FAILED", "system", "创建角色失败: 角色信息对象为空");
                return Result.fail("角色信息无效");
            }
            
            LogUtils.debug(logger, () -> "获取创建角色请求参数: 角色名称=" + role.getRoleName() + ", 角色代码=" + role.getRoleCode() + ", 描述=" + role.getDescription());
            
            // 验证参数
            if (role.getRoleName() == null || role.getRoleName().isEmpty()) {
                LogUtils.warn(logger, "创建角色失败: 角色名称不能为空");
                LogUtils.logBusiness(logger, "ROLE_CREATE_FAILED", "system", "创建角色失败: 角色名称不能为空");
                return Result.fail("角色名称不能为空");
            }
            
            if (role.getRoleCode() == null || role.getRoleCode().isEmpty()) {
                LogUtils.warn(logger, "创建角色失败: 角色代码不能为空");
                LogUtils.logBusiness(logger, "ROLE_CREATE_FAILED", "system", "创建角色失败: 角色代码不能为空");
                return Result.fail("角色代码不能为空");
            }
            
            // 检查角色代码是否已存在
            LogUtils.info(logger, () -> "检查角色代码是否已存在: " + role.getRoleCode());
            if (roleService.checkRoleCodeExists(role.getRoleCode(), null)) {
                LogUtils.warn(logger, "创建角色失败: 角色代码" + role.getRoleCode() + "已存在");
                LogUtils.logBusiness(logger, "ROLE_CREATE_FAILED", "system", "创建角色失败: 角色代码已存在，代码=" + role.getRoleCode());
                return Result.fail("角色代码已存在");
            }
            
            LogUtils.info(logger, () -> "执行创建角色操作，角色名称=" + role.getRoleName() + ", 角色代码=" + role.getRoleCode());
            boolean success = roleService.createRole(role);
            
            if (success) {
                LogUtils.debug(logger, () -> "创建角色成功，角色名称=" + role.getRoleName() + ", 角色代码=" + role.getRoleCode() + ", 新角色ID=" + role.getId());
                LogUtils.logBusiness(logger, "ROLE_CREATE_SUCCESS", "system", "创建角色成功，角色名称=" + role.getRoleName() + ", 角色代码=" + role.getRoleCode() + ", 角色ID=" + role.getId());
                LogUtils.logPerformance(logger, "createRole", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "创建角色请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("创建角色成功");
            } else {
                LogUtils.warn(logger, "创建角色失败: 未知原因，角色名称=" + role.getRoleName() + ", 角色代码=" + role.getRoleCode());
                LogUtils.logBusiness(logger, "ROLE_CREATE_FAILED", "system", "创建角色失败: 未知原因");
                return Result.fail("创建角色失败");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "POST", "/api/system/roles", e);
            LogUtils.error(logger, "创建角色过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "ROLE_CREATE_FAILED", "system", "创建角色失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "createRole", startTime, System.currentTimeMillis());
            return Result.fail("创建角色失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新角色
     * @param id 角色ID
     * @param role 角色信息
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public Result<String> updateRole(@PathVariable Long id, @RequestBody Role role) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "ROLE_UPDATE_ATTEMPT", "system", "尝试更新角色信息");
        LogUtils.logApiRequest(logger, "PUT", "/api/system/roles/" + id, role != null ? role.toString() : "空请求");
        LogUtils.debug(logger, () -> "开始处理更新角色请求，角色ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "更新角色失败: 角色ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "ROLE_UPDATE_FAILED", "system", "更新角色失败: 角色ID无效");
                return Result.fail("角色ID无效");
            }
            
            // 验证请求对象
            if (role == null) {
                LogUtils.warn(logger, "更新角色失败: 角色信息对象为空");
                LogUtils.logBusiness(logger, "ROLE_UPDATE_FAILED", "system", "更新角色失败: 角色信息对象为空");
                return Result.fail("角色信息无效");
            }
            
            LogUtils.debug(logger, () -> "获取更新角色请求参数: 角色名称=" + role.getRoleName() + ", 角色代码=" + role.getRoleCode() + ", 描述=" + role.getDescription());
            
            // 验证参数
            if (role.getRoleName() == null || role.getRoleName().isEmpty()) {
                LogUtils.warn(logger, "更新角色失败: 角色名称不能为空");
                LogUtils.logBusiness(logger, "ROLE_UPDATE_FAILED", "system", "更新角色失败: 角色名称不能为空");
                return Result.fail("角色名称不能为空");
            }
            
            if (role.getRoleCode() == null || role.getRoleCode().isEmpty()) {
                LogUtils.warn(logger, "更新角色失败: 角色代码不能为空");
                LogUtils.logBusiness(logger, "ROLE_UPDATE_FAILED", "system", "更新角色失败: 角色代码不能为空");
                return Result.fail("角色代码不能为空");
            }
            
            // 设置角色ID
            role.setId(id);
            LogUtils.debug(logger, () -> "设置角色ID为路径参数中的ID值: " + id);
            
            // 检查角色是否存在
            LogUtils.info(logger, () -> "检查角色是否存在，角色ID=" + id);
            if (roleService.getRoleById(id) == null) {
                LogUtils.warn(logger, "更新角色失败: ID为" + id + "的角色不存在");
                LogUtils.logBusiness(logger, "ROLE_UPDATE_FAILED", "system", "更新角色失败: 角色不存在，ID=" + id);
                return Result.fail("角色不存在");
            }
            
            // 检查角色代码是否已存在（排除当前角色）
            LogUtils.info(logger, () -> "检查角色代码是否已存在（排除当前角色）: " + role.getRoleCode());
            if (roleService.checkRoleCodeExists(role.getRoleCode(), id)) {
                LogUtils.warn(logger, "更新角色失败: 角色代码" + role.getRoleCode() + "已存在");
                LogUtils.logBusiness(logger, "ROLE_UPDATE_FAILED", "system", "更新角色失败: 角色代码已存在，代码=" + role.getRoleCode());
                return Result.fail("角色代码已存在");
            }
            
            LogUtils.info(logger, () -> "执行更新角色操作，角色ID=" + id + ", 角色名称=" + role.getRoleName() + ", 角色代码=" + role.getRoleCode());
            boolean success = roleService.updateRole(role);
            
            if (success) {
                LogUtils.debug(logger, () -> "更新角色成功，角色ID=" + id + ", 角色名称=" + role.getRoleName() + ", 角色代码=" + role.getRoleCode());
                LogUtils.logBusiness(logger, "ROLE_UPDATE_SUCCESS", "system", "更新角色成功，角色ID=" + id + ", 角色名称=" + role.getRoleName());
                LogUtils.logPerformance(logger, "updateRole", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "更新角色请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("更新角色成功");
            } else {
                LogUtils.warn(logger, "更新角色失败: 未知原因，角色ID=" + id + ", 角色名称=" + role.getRoleName());
                LogUtils.logBusiness(logger, "ROLE_UPDATE_FAILED", "system", "更新角色失败: 未知原因");
                return Result.fail("更新角色失败");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "PUT", "/api/system/roles/" + id, e);
            LogUtils.error(logger, "更新角色过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "ROLE_UPDATE_FAILED", "system", "更新角色失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "updateRole", startTime, System.currentTimeMillis());
            return Result.fail("更新角色失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除角色
     * @param id 角色ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteRole(@PathVariable Long id) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "ROLE_DELETE_ATTEMPT", "system", "尝试删除角色");
        LogUtils.logApiRequest(logger, "DELETE", "/api/system/roles/" + id, null);
        LogUtils.debug(logger, () -> "开始处理删除角色请求，角色ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "删除角色失败: 角色ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "ROLE_DELETE_FAILED", "system", "删除角色失败: 角色ID无效");
                return Result.fail("角色ID无效");
            }
            
            // 检查角色是否存在
            LogUtils.info(logger, () -> "检查角色是否存在，角色ID=" + id);
            if (roleService.getRoleById(id) == null) {
                LogUtils.warn(logger, "删除角色失败: ID为" + id + "的角色不存在");
                LogUtils.logBusiness(logger, "ROLE_DELETE_FAILED", "system", "删除角色失败: 角色不存在，ID=" + id);
                return Result.fail("角色不存在");
            }
            
            LogUtils.info(logger, () -> "执行删除角色操作，角色ID=" + id);
            boolean success = roleService.deleteRole(id);
            
            if (success) {
                LogUtils.debug(logger, () -> "删除角色成功，角色ID=" + id);
                LogUtils.logBusiness(logger, "ROLE_DELETE_SUCCESS", "system", "删除角色成功，角色ID=" + id);
                LogUtils.logPerformance(logger, "deleteRole", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "删除角色请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("删除角色成功");
            } else {
                LogUtils.warn(logger, "删除角色失败: 未知原因，角色ID=" + id);
                LogUtils.logBusiness(logger, "ROLE_DELETE_FAILED", "system", "删除角色失败: 未知原因");
                return Result.fail("删除角色失败");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "DELETE", "/api/system/roles/" + id, e);
            LogUtils.error(logger, "删除角色过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "ROLE_DELETE_FAILED", "system", "删除角色失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "deleteRole", startTime, System.currentTimeMillis());
            return Result.fail("删除角色失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量删除角色
     * @param ids 角色ID列表
     * @return 删除结果
     */
    @DeleteMapping("/batch")
    public Result<String> deleteRoles(@RequestBody List<Long> ids) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "ROLE_BATCH_DELETE_ATTEMPT", "system", "尝试批量删除角色");
        LogUtils.logApiRequest(logger, "DELETE", "/api/system/roles/batch", ids != null ? ids.toString() : "空请求");
        LogUtils.debug(logger, () -> "开始处理批量删除角色请求");
        
        try {
            // 验证参数
            if (ids == null || ids.isEmpty()) {
                LogUtils.warn(logger, "批量删除角色失败: 角色ID列表为空");
                LogUtils.logBusiness(logger, "ROLE_BATCH_DELETE_FAILED", "system", "批量删除角色失败: 角色ID列表为空");
                return Result.fail("请选择要删除的角色");
            }
            
            // 验证ID列表中的每个ID
            for (Long id : ids) {
                if (id == null || id <= 0) {
                    LogUtils.warn(logger, "批量删除角色失败: 存在无效的角色ID: " + id);
                    LogUtils.logBusiness(logger, "ROLE_BATCH_DELETE_FAILED", "system", "批量删除角色失败: 存在无效的角色ID");
                    return Result.fail("角色ID无效");
                }
            }
            
            LogUtils.debug(logger, () -> "获取批量删除角色ID列表，共" + ids.size() + "个角色ID");
            LogUtils.info(logger, () -> "执行批量删除角色操作，角色数量=" + ids.size());
            boolean success = roleService.deleteRoles(ids);
            
            if (success) {
                LogUtils.debug(logger, () -> "批量删除角色成功，删除角色数量=" + ids.size());
                LogUtils.logBusiness(logger, "ROLE_BATCH_DELETE_SUCCESS", "system", "批量删除角色成功，删除角色数量=" + ids.size());
                LogUtils.logPerformance(logger, "deleteRoles", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "批量删除角色请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("批量删除角色成功");
            } else {
                LogUtils.warn(logger, "批量删除角色失败: 未知原因，尝试删除角色数量=" + ids.size());
                LogUtils.logBusiness(logger, "ROLE_BATCH_DELETE_FAILED", "system", "批量删除角色失败: 未知原因");
                return Result.fail("批量删除角色失败");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "DELETE", "/api/system/roles/batch", e);
            LogUtils.error(logger, "批量删除角色过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "ROLE_BATCH_DELETE_FAILED", "system", "批量删除角色失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "deleteRoles", startTime, System.currentTimeMillis());
            return Result.fail("批量删除角色失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新角色状态
     * @param id 角色ID
     * @param status 状态（0-禁用，1-启用）
     * @return 更新结果
     */
    @PutMapping("/{id}/status")
    public Result<String> updateRoleStatus(@PathVariable Long id, @RequestParam Integer status) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "ROLE_STATUS_UPDATE_ATTEMPT", "system", "尝试更新角色状态");
        LogUtils.logApiRequest(logger, "PUT", "/api/system/roles/" + id + "/status", "status=" + status);
        LogUtils.debug(logger, () -> "开始处理更新角色状态请求，角色ID=" + id + ", 新状态=" + status);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "更新角色状态失败: 角色ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "ROLE_STATUS_UPDATE_FAILED", "system", "更新角色状态失败: 角色ID无效");
                return Result.fail("角色ID无效");
            }
            
            // 验证状态值
            if (status == null || (status != 0 && status != 1)) {
                LogUtils.warn(logger, "更新角色状态失败: 状态值无效，只能是0或1，当前值=" + status);
                LogUtils.logBusiness(logger, "ROLE_STATUS_UPDATE_FAILED", "system", "更新角色状态失败: 状态值无效");
                return Result.fail("状态值无效，只能是0或1");
            }
            
            // 检查角色是否存在
            LogUtils.info(logger, () -> "检查角色是否存在，角色ID=" + id);
            if (roleService.getRoleById(id) == null) {
                LogUtils.warn(logger, "更新角色状态失败: ID为" + id + "的角色不存在");
                LogUtils.logBusiness(logger, "ROLE_STATUS_UPDATE_FAILED", "system", "更新角色状态失败: 角色不存在，ID=" + id);
                return Result.fail("角色不存在");
            }
            
            LogUtils.info(logger, () -> "执行更新角色状态操作，角色ID=" + id + ", 新状态=" + (status == 0 ? "禁用" : "启用"));
            boolean success = roleService.updateRoleStatus(id, status);
            
            if (success) {
                LogUtils.debug(logger, () -> "更新角色状态成功，角色ID=" + id + ", 新状态=" + (status == 0 ? "禁用" : "启用"));
                LogUtils.logBusiness(logger, "ROLE_STATUS_UPDATE_SUCCESS", "system", "更新角色状态成功，角色ID=" + id + ", 新状态=" + (status == 0 ? "禁用" : "启用"));
                LogUtils.logPerformance(logger, "updateRoleStatus", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "更新角色状态请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("更新角色状态成功");
            } else {
                LogUtils.warn(logger, "更新角色状态失败: 未知原因，角色ID=" + id + ", 目标状态=" + status);
                LogUtils.logBusiness(logger, "ROLE_STATUS_UPDATE_FAILED", "system", "更新角色状态失败: 未知原因");
                return Result.fail("更新角色状态失败");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "PUT", "/api/system/roles/" + id + "/status", e);
            LogUtils.error(logger, "更新角色状态过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "ROLE_STATUS_UPDATE_FAILED", "system", "更新角色状态失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "updateRoleStatus", startTime, System.currentTimeMillis());
            return Result.fail("更新角色状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查角色代码是否已存在
     * @param roleCode 角色代码
     * @param id 角色ID（更新时使用）
     * @return 检查结果
     */
    @GetMapping("/check-code")
    public Result<Boolean> checkRoleCode(
            @RequestParam String roleCode,
            @RequestParam(required = false) Long id) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "ROLE_CODE_CHECK_ATTEMPT", "system", "尝试检查角色代码是否已存在");
        LogUtils.logApiRequest(logger, "GET", "/api/system/roles/check-code", "roleCode=" + roleCode + ", id=" + (id != null ? id : "空"));
        LogUtils.debug(logger, () -> "开始处理检查角色代码是否已存在请求，角色代码=" + roleCode + ", 排除角色ID=" + id);
        
        try {
            // 验证参数
            if (roleCode == null || roleCode.isEmpty()) {
                LogUtils.warn(logger, "检查角色代码失败: 角色代码不能为空");
                LogUtils.logBusiness(logger, "ROLE_CODE_CHECK_FAILED", "system", "检查角色代码失败: 角色代码不能为空");
                return Result.fail("角色代码不能为空");
            }
            
            LogUtils.info(logger, () -> "执行检查角色代码是否已存在操作，角色代码=" + roleCode + ", 排除角色ID=" + id);
            boolean exists = roleService.checkRoleCodeExists(roleCode, id);
            
            LogUtils.debug(logger, () -> "检查角色代码完成，角色代码=" + roleCode + ", 检查结果=" + (exists ? "已存在" : "不存在"));
            LogUtils.logBusiness(logger, "ROLE_CODE_CHECK_SUCCESS", "system", "检查角色代码完成，角色代码=" + roleCode + ", 结果=" + (exists ? "已存在" : "不存在"));
            LogUtils.logPerformance(logger, "checkRoleCode", startTime, System.currentTimeMillis());
            
            LogUtils.info(logger, () -> "检查角色代码请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
            return Result.success(exists);
        } catch (Exception e) {
            LogUtils.logApiError(logger, "GET", "/api/system/roles/check-code", e);
            LogUtils.error(logger, "检查角色代码过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "ROLE_CODE_CHECK_FAILED", "system", "检查角色代码失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "checkRoleCode", startTime, System.currentTimeMillis());
            return Result.fail("检查角色代码失败: " + e.getMessage());
        }
    }
}